package com.zsr.system.service.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.zsr.common.config.OssConfig;
import com.zsr.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 阿里云 OSS
 */
@Service
public class OssService {

    @Autowired
    private OssConfig ossConfig;

    public OSS getClient() {
        return new OSSClientBuilder()
            .build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
    }

    /**
     * 上传文件到 OSS
     * @param file 文件
     * @param dir 目录（如 avatar/2025/10/24/）
     * @return 外网访问 URL
     */
    public String upload(MultipartFile file, String dir) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileName = dir + System.currentTimeMillis() + "_" + originalFilename;

        OSS ossClient = getClient();
        try {
            PutObjectRequest request = new PutObjectRequest(
                ossConfig.getBucketName(),
                fileName,
                file.getInputStream()
            );
            ossClient.putObject(request);

            // 返回可访问的 URL
            return ossConfig.getDomain() + "/" + fileName;
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 删除文件
     */
    public void delete(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) return;
        String key = fileUrl.replace(ossConfig.getDomain() + "/", "");
        OSS ossClient = getClient();
        try {
            ossClient.deleteObject(ossConfig.getBucketName(), key);
        } finally {
            ossClient.shutdown();
        }
    }
}